<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useTeachingHook } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "@iconify-icons/ep/delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { CommonUtils } from "@/utils/common";
import TeachingFormModal from "@/views/cafuc/submit/teaching/teaching-form-modal.vue";
import TeachingImportModal from "@/views/cafuc/submit/teaching/teaching-import-modal.vue";
import EditPen from "@iconify-icons/ep/edit-pen";
import { TeachingWorkloadPageResponse } from "@/api/performance/teaching";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Upload from "@iconify-icons/ep/upload";
import { getAllUsersSimpleApi, type UserSimpleDTO } from "@/api/system/user";
import { getDeptTree } from "@/api/system/dept";

defineOptions({
  name: "teachingList"
});

const tableRef = ref();

const searchFormRef = ref();
const {
  searchFormParams,
  pageLoading,
  columns,
  dataList,
  pagination,
  timeRange,
  defaultSort,
  multipleSelection,
  onSearch,
  resetForm,
  onSortChanged,
  exportAllExcel,
  getTeachingWorkloadList,
  handleDelete,
  handleBulkDelete
} = useTeachingHook();

// 用户搜索相关
const allUsers = ref<UserSimpleDTO[]>([]);
const userOptions = ref<UserSimpleDTO[]>([]);

async function fetchAllUsersSimple() {
  try {
    const { data } = await getAllUsersSimpleApi();
    allUsers.value = data || [];
    userOptions.value = allUsers.value;
  } catch (e) {
    console.error(e);
  }
}

function remoteSearchUsers(query: string) {
  const q = (query || "").trim();
  if (!q) {
    userOptions.value = allUsers.value;
    return;
  }
  const lower = q.toLowerCase();
  userOptions.value = allUsers.value.filter(u =>
    (u.nickname || "").toLowerCase().includes(lower) ||
    (u.deptName || "").toLowerCase().includes(lower)
  );
}

function getUserLabel(u: UserSimpleDTO) {
  const name = u.nickname || "";
  const dept = u.deptName || "";
  return dept ? `${name}（${dept}）` : name;
}

// 部门树相关
const deptTree = ref([]);

onMounted(async () => {
  // 加载用户列表
  await fetchAllUsersSimple();
  
  // 加载部门树
  try {
    const { data } = await getDeptTree();
    if (data) {
      // 转换数据格式
      const convertDeptTree = (nodes) => {
        return nodes.map(node => ({
          value: node.id,
          label: node.label,
          children: node.children ? convertDeptTree(node.children) : undefined
        }));
      };
      // 若 data 本身是数组，直接转换
      if (Array.isArray(data)) {
        deptTree.value = convertDeptTree(data);
      } else {
        // 若 data 不是数组，将其包裹成数组再转换
        deptTree.value = convertDeptTree([data]);
      }
    }
  } catch (error) {
    console.error('获取部门树数据失败:', error);
  }
});

const opType = ref<"add" | "update">("add");
const modalVisible = ref(false);
const opRow = ref<TeachingWorkloadPageResponse>();
function openDialog(type: "add" | "update", row?: TeachingWorkloadPageResponse) {
  opType.value = type;
  opRow.value = row;
  modalVisible.value = true;
}

const importModalVisible = ref(false);
function openImportDialog() {
  importModalVisible.value = true;
}
</script>

<template>
  <div class="main">
    <!-- 搜索栏 -->
    <el-form
      ref="searchFormRef"
      :inline="true"
      :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
      <el-form-item label="用户" prop="userId">
        <el-select
          v-model="searchFormParams.userId"
          filterable
          remote
          reserve-keyword
          placeholder="搜索并选择用户"
          :remote-method="remoteSearchUsers"
          clearable
          class="!w-[200px]"
        >
          <el-option
            v-for="u in userOptions"
            :key="u.userId"
            :label="getUserLabel(u)"
            :value="u.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-cascader
          v-model="searchFormParams.deptId"
          :options="deptTree"
          :props="{
            value: 'value',
            label: 'label',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          placeholder="请选择部门"
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="考核年度" prop="assessmentYear">
        <el-input
          v-model="searchFormParams.assessmentYear"
          placeholder="请输入考核年度"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>

 
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="pageLoading"
          @click="onSearch(tableRef)"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          @click="resetForm(searchFormRef, tableRef)"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- table bar 包裹  table -->
    <PureTableBar title="教学工作量列表" :columns="columns" @refresh="onSearch">
      <!-- 表格操作栏 -->
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog('add')"
        >
          新增教学工作量
        </el-button>
        <el-button
          type="primary"
          :icon="useRenderIcon(Upload)"
          @click="openImportDialog"
        >
          导入数据
        </el-button>
        <el-button
          type="danger"
          :icon="useRenderIcon(Delete)"
          @click="handleBulkDelete(tableRef)"
        >
          批量删除
        </el-button>
        <el-button
          type="primary"
          @click="CommonUtils.exportExcel(columns, dataList, '教学工作量列表')"
        >单页导出</el-button
        >
        <el-button type="primary" @click="exportAllExcel">全部导出</el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="pageLoading"
          :size="size"
          adaptive
          :data="dataList"
          :columns="dynamicColumns"
          :default-sort="defaultSort"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="getTeachingWorkloadList"
          @page-current-change="getTeachingWorkloadList"
          @sort-change="onSortChanged"
          @selection-change="
            rows => (multipleSelection = rows.map(item => item.id))
          "
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="openDialog('update', row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`是否确认删除编号为${row.id}的这条教学工作量`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="danger"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <teaching-form-modal
      v-model="modalVisible"
      :type="opType"
      :row="opRow"
      @success="onSearch"
    />
    <teaching-import-modal
      v-model="importModalVisible"
      @success="onSearch"
    />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
